<script lang="ts" setup>
import {ref, onBeforeMount,computed} from 'vue'
import {updateOrderAPI,getDetailOrderListAPI} from "@/apis/order.js";
import {useUserStore} from "@/stores/user.js";
import router from "@/router/index.js";
import MapContainer from "@/components/base/MapContainer.vue";
import {getTradeStatusAPI} from '@/apis/alipay'
import EvaluationDialog from "@/components/EvaluationDialog.vue";
import { ElMessageBox, ElMessage } from 'element-plus'

const radio=ref('1')
const orderList=ref([])

onBeforeMount(()=>{
  getOrderList()
})

const getOrderList=async ()=>{
  const res=await getDetailOrderListAPI(useUserStore().userInfo.uid)
  if(res.code===200){
    //过滤掉被删除的订单
    orderList.value=res.data.filter(item=>item.status!==6)
    //与支付宝中的订单进行状态同步
    await updateOrderWithAlipay()
    //按订单号排序,订单号大的在前面
    orderList.value.sort(function(a, b){
      return b.oid - a.oid
    })
  }
}

const updateOrderWithAlipay=async ()=>{
  orderList.value.forEach(order=>{
    //筛选所有状态为待付款的订单
    if(order.status===0){
      //查询在支付宝中的交易状态
      getTradeStatusAPI(order.oid).then(res=>{
        if(res.tradeStatus==='TRADE_SUCCESS'){
          console.log('订单未同步',order.oid)
          //执行更新
          order.status=2
          updateOrderAPI(order.oid, 2)
        }
      })
    }
  })
}

const pageNumber=ref(1)
const perPageSize=4
const total=ref(0)

const orderListFilter=computed(()=>{
  //分类
  const radioOrderList=orderList.value.filter(order=>{
    let matchesRadio=false
    switch (radio.value) {
      case '1':matchesRadio=true;break
      case '2':matchesRadio=order.status === 0;break
      case '3':matchesRadio=order.status===2;break
      case '4':matchesRadio=order.status===3;break
      case '5':matchesRadio=order.status===1||order.status===4;break
      case '6':matchesRadio=order.status===5||order.status===7;break
    }
    return matchesRadio
  })
  total.value=radioOrderList.length
  //分页
  let start=(pageNumber.value-1)*perPageSize
  let end=pageNumber.value*perPageSize-1>radioOrderList.length?radioOrderList.length:pageNumber.value*perPageSize
  return radioOrderList.slice(start,end)
})

function getStatusText(status):string {
  switch (status) {
    case 0:return '待付款';
    case 1:return '已取消';
    case 2:return '待发货';
    case 3:return '待收货';
    case 4:return '已完成';
    case 5:return '等待卖家退款';
    case 7:return '已退款';
  }
}


function timestampToTime(timestamp) {
  // 处理不同格式的时间戳
  let date;
  
  if (typeof timestamp === 'number') {
    // 如果是数字时间戳
    date = timestamp.toString().length === 10 ? new Date(timestamp * 1000) : new Date(timestamp);
  } else if (typeof timestamp === 'string') {
    // 如果是字符串时间戳或日期字符串
    if (/^\d+$/.test(timestamp)) {
      // 纯数字字符串
      date = timestamp.length === 10 ? new Date(parseInt(timestamp) * 1000) : new Date(parseInt(timestamp));
    } else {
      // 日期字符串（如后端返回的格式化时间）
      date = new Date(timestamp);
    }
  } else {
    // 其他情况返回空字符串
    return '';
  }
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    console.warn('Invalid timestamp:', timestamp);
    return '';
  }
  
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
  var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  var h = String(date.getHours()).padStart(2, '0') + ':';
  var m = String(date.getMinutes()).padStart(2, '0') + ':';
  var s = String(date.getSeconds()).padStart(2, '0');
  return Y+M+D+h+m+s;
}

function handleClick(oid,option) {
  const message=['确认要取消订单吗', '确认要退款吗', '是否已收到货']
  const successMsg=['订单取消成功','已申请退款','已确认收货']
  ElMessageBox.confirm(
      message[option-1],
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        let status
        switch (option) {
          case 1: status=1;break
          case 2: status=5;break
          case 3: status=4;break
        }
        updateOrderAPI(oid, status).then((res)=>{
          if (res.code===200){
            ElMessage({
              type: 'success',
              message: successMsg[option-1],
            })
            //更新订单列表
            getOrderList()
          }else{
            ElMessage({
              type: 'error',
              message: '操作失败',
            })
          }
        })

      })
      .catch(() => {
        //用户取消操作
      })
}

function deleteOrder(oid) {
  ElMessageBox.confirm(
      '确认删除订单？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
        updateOrderAPI(oid, 6).then((res)=>{
          if (res.code===200){
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            //更新订单列表
            getOrderList()
          }else{
            ElMessage({
              type: 'error',
              message: '操作失败',
            })
          }
        })
      }).catch(() => {
        //用户取消操作
      })
}

function toPay(oid,total) {
  const orderList=[oid]
  router.push({
    path: "/pay",
    query: {
      date:new Date().getTime(),
      total:total,
      data:JSON.stringify(orderList),
      type:'order'
    }
  })
}


function urge() {
  ElMessage({
    type: 'success',
    message: '已催促商家尽快发货',
  })
}
// OSS配置
const OSS_BASE_URL = 'https://zdbackend.oss-cn-guangzhou.aliyuncs.com/20241102/product-img/'
// 获取商品图片路径
function getImageUrl(imageName) {
  if (!imageName) return ''
  return `${imageName}`
}

const mapDialogVisible=ref(false)
const refundDialogVisible=ref(false)
const refundStep=ref(1)
const evaluationDialogVisible=ref(false)
const goodsToEvaluate=ref([])

const currentOrder = ref(null);
const startAddress = ref('');
const endAddress = ref('');

// 查看物流
function showLogistics(order) {
  currentOrder.value = order;
  // 拼接起点和终点地址
  // 注意：这里的字段名（如 shop.province, address.city）是基于数据库文档的推断，需要与后端API的实际返回结果保持一致
  startAddress.value = `${order.shop.province || ''} ${order.shop.city || ''} ${order.shop.area || ''} ${order.shop.address || ''}`;
  endAddress.value = `${order.address.province || ''} ${order.address.city || ''} ${order.address.area || ''} ${order.address.town || ''} ${order.address.address || ''}`;
  mapDialogVisible.value = true;
}


function handleEvaluate(goods) {
  // 检查是否已经评价过
  const hasEvaluated = goods.some(item => item.evaluation)
  if (hasEvaluated) {
    ElMessage.info('您已经评价过此商品了')
    return
  }
  
  // 准备要评价的商品数据
  goodsToEvaluate.value = goods.map(item => ({
    gid: item.gid,
    goodsName: item.title,
    goodsImg: [item.goodsImg],
    price: item.unit_price
  }))
  
  // 显示评价对话框
  evaluationDialogVisible.value = true
}

</script>

<template>
<div class="page">
<div class="header">
  <el-radio-group v-model="radio" size="large">
    <el-radio-button label="全部订单" value="1" />
    <el-radio-button label="待付款" value="2" />
    <el-radio-button label="待发货" value="3" />
    <el-radio-button label="待收货" value="4" />
    <el-radio-button label="已完成" value="5" />
    <el-radio-button label="退款" value="6" />
  </el-radio-group>
</div>

  <div class="bar">
    <div style="width: 380px">
      <span >宝贝</span>
    </div>
    <div style="">
      <span >单价</span>
    </div>
    <div style="margin-left: 50px">
      <span>数量</span>
    </div>
    <div style="margin-left: 80px">
      <span>实付款</span>
    </div>
    <div style="margin-left: 50px">
      <span >交易状态</span>
    </div>
    <div style="margin-left: 60px">
      <span >交易操作</span>
    </div>

  </div>

  <div class="body">
    <div class="orderBar" v-for="(item,index) in orderListFilter">

      <div class="upper">
        <div style="width: 200px">
          <span style="line-height: 40px;font-size: 12px">
            下单时间：{{timestampToTime(item.created_date)}}</span>
        </div>

        <div style="width: 100px;font-size: 12px">
          <span style="line-height: 40px">订单号：</span>
          {{ item.oid }}
        </div>

        <el-icon class="delIcon" v-show="item.status===1||item.status===4||item.status===7"
                 size="25"
                 style="margin-left: auto;
                 margin-right: 20px;
                 line-height: 40px"
                 @click="deleteOrder(item.oid)">
          <Delete /></el-icon>
      </div>

      <div class="orderPanel" >
        <div class="left" style="min-height: 120px;height:auto;width: 650px;">
          <div class="goods" v-for="goods in item.goods">
            <div>
              <img :src="goods.goodsImg" style="height: 90px;width: 90px" alt="">
            </div>
            <div style="width: 260px;margin-left: 10px">
              <span style="font-size: 12px">{{ goods.title }}</span>
              <br>&nbsp;
              <el-tag type="warning" style="margin-left: 5px;" size="small" v-for="tag in goods.tags">{{tag}}</el-tag>
            </div>
            <div style="width: 100px">
              &nbsp;&nbsp;￥{{goods.unit_price}}
            </div>
            <div style="width: 100px">
              {{ goods.amount }}
            </div>
            <div style="width: 80px">
              <span style="font-size: 14px;font-weight: bold">￥{{goods.sub_price}}</span>
            </div>
<!--            分割线-->
            <div style="width: 1px;height: 100px;background-color: rgba(204,204,204,0.67)"></div>
          </div>
        </div>



        <div class="right" style="height: 100px;width: 450px;">
          <div class="orderOption">
            <div style="width: 100px">
              {{ getStatusText(item.status) }}
            </div>
            <div style="width: 190px">
              <el-button v-if="item.status===0" style="background-color: #ff5000;color: white" @click="toPay(item.oid,item.total_price)">
                去付款</el-button>
              <el-button v-if="item.status===0" style="background-color: #ff5000;color: white" @click="handleClick(item.oid,1)" >
                取消订单</el-button>
              <el-button v-if="item.status===2" style="background-color: #409eff;color: white" @click="urge" >
                催发货</el-button>
              <el-button v-if="item.status===2" style="background-color: #ff5000;color: white" @click="handleClick(item.oid,2)">
                申请退款</el-button>
              <el-button v-if="item.status===3" style="background-color: #ff5000;color: white" @click="handleClick(item.oid,3)">
                确认收货</el-button>
              <el-button v-if="item.status===3" style="background-color: #409eff;color: white" @click="showLogistics(item)">
                查看物流</el-button>
              <el-button v-if="item.status===4" style="background-color: #ff5000;color: white" @click="router.push(`/detail/${item.goods[0].gid}`)">
                再买一次</el-button>
              <el-button v-if="item.status===4" style="background-color: #ff5000;color: white" @click="handleEvaluate(item.goods)">
                评价</el-button>
              <el-button v-if="item.status===5" style="background-color: #ff5000;color: white" @click="refundDialogVisible=true">
                查看退款进度</el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="footer">
        <span style="font-size: 12px;line-height: 40px">订单备注：{{item.order_message}}</span>
      </div>
    </div>
  </div>
  <el-empty v-if="orderList.length===0" description="暂无订单" />
  <div class="example-pagination-block" style="justify-items: center">
    <el-pagination layout="prev, pager, next" :page-size="perPageSize" :total="total" v-model:current-page="pageNumber" />
  </div>
  <el-dialog v-model="mapDialogVisible" title="物流进度" width="800">
    <MapContainer v-if="mapDialogVisible" :mapId="'logisticsMap_' + currentOrder.oid" :startAddress="startAddress" :endAddress="endAddress" style="width: 100%;height: 400px;"></MapContainer>
  </el-dialog>
  <el-dialog v-model="refundDialogVisible" title="退款进度" width="800">
    <el-steps style="width: 100%" :active="refundStep" finish-status="success">
      <el-step title="申请退款" description="您已提交了退款申请" />
      <el-step title="商家处理" description="等待商家退款"/>
      <el-step title="退款成功" description="商家已同意退款"/>
    </el-steps>
  </el-dialog>
  
  <EvaluationDialog 
    v-model:visible="evaluationDialogVisible" 
    :goods="goodsToEvaluate" 
    @success="getOrderList" 
  />
</div>
</template>

<style scoped lang="less">
.page{
  width: 990px;
  min-height: 500px;
  height: auto;
  background-color: white;
  border-radius: 10px;

  padding: 20px;
}
.orderBar{
  width: 950px;
  min-height: 160px;
  height: auto;
  background-color: #ffffff;
  border: rgba(181, 183, 185, 0.65) 1px solid;
  border-radius: 8px;
  margin-top: 15px;
}
.orderPanel{
  display: flex;
  flex-direction: row;
}
.orderOption{
  padding: 15px 0;
  display: flex;
  flex-direction: row;
}
.upper{
  width: 100%;
  height: 40px;
  background-color: rgba(232, 232, 234, 0.66);
  padding: 0 10px;
  border-radius: 8px 8px 0 0;
  display: flex;
  flex-direction: row;
}

.footer{
  width: 100%;
  height: 40px;
  background-color: rgba(232, 232, 234, 0.66);
  padding: 0 10px;
  border-radius: 0 0 8px 8px ;
}
.goods{
  padding: 15px;
  display: flex;
  flex-direction: row;
}
.bar{
  background-color: rgba(232, 232, 234, 0.66);
  border-radius: 8px;
  margin-top: 20px;

  display: flex;
  flex-direction: row;
}
.bar div{
  //width: 100px;
  text-align: center
}
.bar span{
  line-height: 40px
}
.delIcon:hover{
  cursor: pointer;
}
</style>